use actix_web::{Responder, web, HttpResponse};
use serde::{Serialize, Deserialize};
use serde_json::json;

use crate::{model::{order_add_dto::OrderAddDto, Orderitem, Goodimg, order::Order}, resp::Resp, api::{good_api::{QueryGoodVoByGidsDto, RespOfQueryGoodVoByGids, self}}, interface::dto::Dto, util::{logger, date_util}, RB};

#[allow(unused_must_use)]
pub async fn main(order_add_dto: web::Json<OrderAddDto>) -> impl Responder {
    let order_add_dto: OrderAddDto = order_add_dto.into_inner();
    let gitems = order_add_dto.glist.clone();
    match gitems {
        Some(_) => {
            // let gitems = gitems.unwrap();
        },
        None => {
            return HttpResponse::Ok().json(json!(Resp::fail("请选择商品", -1, ())));
        },
    }
    // 由于当前版本商城只有一个商户，不按商户把商品分组拆单了
    let mut gitems = gitems.unwrap();
    // 遍历glist获取gids
    let mut gids: Vec<String> = vec![];
    for gitem in gitems.iter() {
        gids.push(gitem.gid.clone().unwrap());
    }
    let query_good_vo_by_gids_dto: QueryGoodVoByGidsDto = QueryGoodVoByGidsDto {gids: gids.clone()};
    let response: RespOfQueryGoodVoByGids = good_api::query_goodvo_by_gids(query_good_vo_by_gids_dto).await;
    if response.code != 200 {
        return HttpResponse::Ok().json(json!(Resp::bad("商品服务异常", -1, ())));
    }
    if response.data.clone().unwrap().len()<gids.len() {  //查询到的数量不足
        return HttpResponse::Ok().json(json!(Resp::bad("有商品不存在", -1, ())));
    }
    // 检测完毕，生成order实体，最后在插入
    let mut rb = RB.clone();
    let mut order = order_add_dto.to_po();
    order.uid = Some(gitems[0].clone().uid.unwrap());
    let mut good_vos = response.data.clone().unwrap();
    //gitems和good_vos都按id排好序，顺序相同便于使用下标读取操作
    gitems.sort_by(|a,b|a.gid.clone().unwrap().cmp(&b.gid.clone().unwrap()));
    good_vos.sort_by(|a,b|a.gid.clone().cmp(&b.gid.clone()));
    let mut money: f64 = 0.00;
    for (idx, good_vo) in good_vos.iter().enumerate() {
        let gitem_tmp = gitems.get(idx).unwrap().clone();
        let price: f64 = good_vo.gprice.clone().parse().unwrap();
        let num: f64 = gitem_tmp.num.clone().unwrap() as f64;
        money = money + price * num;
        let good_vo_tmp = good_vo.clone();
        let orderitem = Orderitem::init_with_good_vo(order.oid.clone().unwrap(), good_vo_tmp.clone(), gitem_tmp);
        let imglist = good_vo_tmp.gimgpath.clone();
        //插入orderitem到数据库
        rb.query(&Orderitem::insert_avoid_id(orderitem), vec![]);
        //插入图片，如果没收录过这个商品
        {
            let sql = format!("select * from goodimg where gid={:?}", good_vo.gid); //有过肯定就收录过
            let rst: Result<Option<Goodimg>, rbatis::rbdc::Error> = rb.query_decode(&sql, vec![]).await;
            let rst: Option<Goodimg> = rst.unwrap();
            match rst {
                Some(_) => {
                    //有则跳过
                },
                None => {
                    for img in imglist.clone().iter() {
                        let goodimg = Goodimg::init(Some(good_vo.gid.clone()), Some(img.to_string()));
                        logger::debug(format!("即将插入图片:{}",json!(goodimg).to_string()));
                        Goodimg::insert(&mut rb, &goodimg);
                    }   
                }
            }
        }
    }
    order.money = Some(money.to_string());
    let stime = date_util::now_time(); //下单时间
    order.stime = Some(stime.clone());
    //插入order
    Order::insert(&mut rb, &order).await;
    let log_str = format!("生成订单{}, 生成时间:{}", order.oid.clone().unwrap(), stime);
    logger::info(log_str);
    HttpResponse::Ok().json(json!(Resp::ok("订单提交成功", 1, Data{oid: order.oid.unwrap()})))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Data {
    oid: String
}
